<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../Ajax—资料/day3/day3/素材/lib/bootstrap.css">
    <script src="../Day1/jquery-3.6.min.js"></script>
</head>

<body>
    <input type="file" name="" id="file1">
    <button id="btnupload">上传文件</button>
    <!-- 进度条 -->
    <div class="progress" style="width: 500px;margin: 15px, 10px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%" id="procent">
            0%
        </div>
    </div>
    <br />
    <img src="" alt="" id="img" width="800">

    <script>
        var btnupload = document.querySelector('#btnupload');
        //2.为按钮绑定单击事件
        btnupload.addEventListener('click', function () {
            //3.获取到用户选择的文件列表
            var files = document.querySelector('#file1').files;
            if (files.length <= 0) {
                return alert('请选择要上传的文件');
            }
            var fd = new FormData();
            //将用户选择的文件添加到FormData
            fd.append('avatar', files[0]);

            var xhr = new XMLHttpRequest();

            //监听文件上传进度
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    //计算上传的进度
                    var procent = Math.ceil((e.loaded / e.total) * 100);
                    console.log(procent);
                    //动态设置进度条
                    $('#procent').attr('style', 'width:' + procent + '%').html(procent + '%');
                }
            }

            xhr.upload.onload = function () {
                $('#procent').removeClass().addClass('progress-bar progress-bar-success')
            }


            xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
            xhr.send(fd);

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    if (data.status === 200) {
                        document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url;
                    } else {
                        console.log('失败');
                    }
                }
            }
        })
    </script>
</body>

</html>